//1.载入模块儿express

const express = require("express");

let fs = require("fs");

const path = require("path");

const app = express();

//设置端口
app.listen("3080",()=>{
    console.log("3080端口已经启动");
})



app.get("/login",(req,res)=>{
   res.sendFile(path.join(__dirname,'login.html'));
})
app.get("/register",(req,res)=>{
    res.sendFile(path.join(__dirname,'register.html'));
 })
 app.get("/doregister",(req,res)=>{
     let {username,pwd,repwd} = req.query;
     if(username == "" || pwd == "" || repwd == "")
     {
         res.send(`<scrit>alert("输入信息不得为空")location.href='/register'</script>`);
         return;

     }
     else if(pwd != repwd)
      {
        res.send(`<scrit>alert("两次输入密码不一致");location.href='/register'</script>`);
        return;
      }
      else
      {
      let content = fs.readFileSync("person.json");
      let userinfo = JSON.parse(content.toString());
      console.log(userinfo);
     let result = userinfo.find((value)=>{
           return value.username == username;
         })
         if(result)
         {
             res.send(`<script>alert("该用户已经存在");location.href='/register'</script>`)
             return;
         }
         else
         {
            userinfo.push(req.query);
            fs.writeFileSync("person.json",JSON.stringify(userinfo));
            res.send("<script>alert('注册成功');location.href='/login'</script>");
            return;
         }
      }


    
 })
 app.get("/dologin",(req,res)=>{
     let {username,pwd} = req.query;
     console.log(username);
    let txt = fs.readFileSync("person.json");
    let userinfo = JSON.parse(txt);
    let result = userinfo.find((value)=>{
        return value.username == username && value.pwd == pwd;
    })
    if(result)
    {
        res.send(`<script>alert("登录成功");</script>`)
        return;
    }
   else
   {
    res.send(`<script>alert("用户名或者密码错误");</script>`)
    return;
   }
 })
 app.all("*",(req,res)=>{
     res.send("404错误");

 })